package com.hanshg.cherry.config.aspect;

import com.hanshg.cherry.config.target.Logger;
import com.hanshg.cherry.dto.LoginUser;
import com.hanshg.cherry.model.SysLog;
import com.hanshg.cherry.service.log.LogService;
import com.hanshg.cherry.util.http.HttpContextUtil;
import com.hanshg.cherry.util.http.IPUtils;
import com.hanshg.cherry.util.core.UserAgentUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 日志断言类
 * @author 柠檬水
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    private LogService logService;

    private static final ThreadLocal<SysLog> LOCAL_INFO = ThreadLocal.withInitial(() -> new SysLog());

    @Pointcut("@annotation(com.hanshg.cherry.config.target.Logger)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        // 执行时长（毫秒）
        long endTime = System.currentTimeMillis();
        // 保存日志
        saveLog(point, (endTime - beginTime));
        return result;
    }

    private void saveLog(ProceedingJoinPoint joinPoint, Long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = LOCAL_INFO.get();
        Logger logAnnotation = method.getAnnotation(Logger.class);
        if (null != logAnnotation) {
            // 注解上的描述
            sysLog.setOperation(logAnnotation.value());
            sysLog.setType(logAnnotation.type());
        }
        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
//        // 请求的方法参数值
//        Object[] args = joinPoint.getArgs();
//        // 请求的方法参数名称
//        LocalVariableTableParameterNameDiscoverer nameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
//        String[] parameterNames = nameDiscoverer.getParameterNames(method);
//
//        if (null != args && null != parameterNames) {
//            String params = "";
//            for (int i = 0; i < args.length; i++) {
//                params += " " + parameterNames[i] + " : " + args[i];
//            }
//            sysLog.setParams(params);
//        }
        //获取登录信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser= (LoginUser) authentication.getPrincipal();
        //保存用户名
        sysLog.setUsername(loginUser.getUsername());
        // 获取request
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        //浏览器名称
        String borderName = UserAgentUtils.getBorderName(request);
        sysLog.setBorderName(borderName);
        //使用的操作系统
        String osName = UserAgentUtils.getOsName(request);
        sysLog.setOsName(osName);
        // 设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));
        // 保存系统日志
        try {
            logService.saveLog(sysLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
